﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AnesSystem.Models;
using AnesSystem.ViewModels;
using AnesSystem.Services;
using System.Threading;
using System.Windows.Threading;
using Common;

namespace AnesSystem
{
    public class AnesVitalSignDataCache : VitalSignDataCache
    {
        #region Variables


        #endregion


        #region Constructor
        public AnesVitalSignDataCache(EventDataCache eventData,String patientId)
        {
            EventData = eventData;
            this.PatientId = patientId;
            Captured += AnesVitalSignDataCache_Captured;
        }

        private void AnesVitalSignDataCache_Captured(object sender, CaptureVitalArgs e)
        {
            ChangeVitalCache(e.PatientVitalSigns);
        }

        #endregion


        #region Properties
        public int CurTotalPage
        {
            get
            {
                return CurPatientLink.Status.TotalPage;
            }
        }

        #endregion


        #region 依赖属性


        #endregion


        #region Event


        #endregion


        #region PrivateMethods


        #endregion


        #region Public/ProtectedMethods
        protected override void AddParamTimeData(int page)
        {
            DateTime date = new DateTime();
            foreach (Dictionary<DateTime, PatientVitalSignsModel> bedsideMap in _bedsideObservableList)
            {
                date = CurPatientLink.Status.AnesRecordStartTime;
                ConfigVitalSignsModel vitalSigns = DataManager.Instance.GetVitalSignsByCode(bedsideMap[date].Code);
                date.AddHours((CurPatientLink.Status.TotalPage - page) * 4);
                for (int i = 0; i < 48 * CurTotalPage; i++)
                {
                    bedsideMap.Add(date, CreateBedside(vitalSigns, date));
                    date = date.AddMinutes(5);
                }
                bedsideMap.Add(date, CreateBedside(vitalSigns, date));
                AddBedsideHistoryData(bedsideMap, vitalSigns, date);
            }
        }
        public override void AddConfigParam(ConfigVitalSignsModel vitalSigns)
        {
            if (_bedsideMapMap.ContainsKey(vitalSigns.code))
            {
                return;
            }
            Dictionary<DateTime, PatientVitalSignsModel> bedsideMap = new Dictionary<DateTime, PatientVitalSignsModel>();
            DateTime date = new DateTime();

            date = (CurPatientLink.Status.AnesRecordStartTime.Equals(new DateTime()) ? CurPatientLink.Status.InRoomTime : CurPatientLink.Status.AnesRecordStartTime);

            for (int i = 0; i < 48 * CurTotalPage; i++)
            {

                bedsideMap.Add(date, CreateBedside(vitalSigns, date));
                date = date.AddMinutes(5);
            }
            bedsideMap.Add(date, CreateBedside(vitalSigns, date));
            AddBedsideHistoryData(bedsideMap, vitalSigns, date);
            foreach (var item in bedsideMap.Values.ToList())
            {
                item.PropertyChanged += PatientVitalSigns_PropertyChanged;
            }
            _bedsideMapMap.Add(vitalSigns.code, bedsideMap);
            _bedsideObservableList.Add(bedsideMap);

            if (vitalSigns.showWay == Constants.BEDSIDE_SHOW_METHOD_TREND || _besideTableObservableList.Count >= 10)
            {
                _besideLineObservableList.Add(bedsideMap);
            }
            else
            {
                _besideTableObservableList.Add(bedsideMap);
            }
        }
        public override void RemoveConfigParam(ConfigVitalSignsModel vitalSigns)
        {
            if (_bedsideMapMap.ContainsKey(vitalSigns.code))
            {
                Dictionary<DateTime, PatientVitalSignsModel> bedsideMap = _bedsideMapMap[vitalSigns.code];
                _bedsideMapMap.Remove(vitalSigns.code);
                _besideLineObservableList.Remove(bedsideMap);
                _besideTableObservableList.Remove(bedsideMap);
                _bedsideObservableList.Remove(bedsideMap);
            }

        }

        protected override void PatientVitalSigns_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            {
                try
                {

                    DateTime outRoomTime = CurPatientLink.Status.OutRoomTime;
                    DateTime inRoomTime = CurPatientLink.Status.InRoomTime;
                    PatientVitalSignsModel patientVitalSignsModel = sender as PatientVitalSignsModel;
                    if (!string.IsNullOrEmpty(patientVitalSignsModel.ModValue))
                    {
                        if (!patientVitalSignsModel.Code.Equals("param_I:E") && !patientVitalSignsModel.Code.Equals("param_ECG"))
                        {
                            double result = 0;
                            bool flag = double.TryParse(patientVitalSignsModel.ModValue, out result);
                            if (!flag)
                            {
                                patientVitalSignsModel.ModValue = "";
                            }
                        }
                    }
                    int showWay = -1;
                    if (DataManager.Instance.Code2signs.ContainsKey(patientVitalSignsModel.Code))
                    {
                        showWay = DataManager.Instance.Code2signs[patientVitalSignsModel.Code].showWay;
                    }

                    if (!outRoomTime.Equals(new DateTime()))
                    {
                        if (patientVitalSignsModel.CaptureTime.CompareTo(outRoomTime) > 0)
                        {

                            Common.LogHelper.Info(this.GetType(), "已出室，该参数无效");
                            if (!string.IsNullOrEmpty(patientVitalSignsModel.ModValue))
                            {
                                patientVitalSignsModel.ModValue = "";
                            }
                            return;

                        }
                    }
                    if (!inRoomTime.Equals(new DateTime()))
                    {
                        if (patientVitalSignsModel.CaptureTime.CompareTo(inRoomTime) < 0)
                        {
                            Common.LogHelper.Info(this.GetType(), "未入室，该参数无效");
                            if (!string.IsNullOrEmpty(patientVitalSignsModel.ModValue))
                            {
                                patientVitalSignsModel.ModValue = "";
                            }
                            return;

                        }
                    }
                    if (patientVitalSignsModel.Code.Equals(Constants.PARAM_RESP_CODE))
                    {
                        if (IsInRespCtrlTime(patientVitalSignsModel.CaptureTime))
                        {
                            if (!string.IsNullOrEmpty(patientVitalSignsModel.ModValue))
                            {
                                patientVitalSignsModel.ModValue = "";
                            }
                            return;
                        }
                    }
                    if (patientVitalSignsModel.Code.Equals(Constants.PARAM_CTRL_RESP_CODE))
                    {
                        if (!IsInRespCtrlTime(patientVitalSignsModel.CaptureTime))
                        {
                            if (!string.IsNullOrEmpty(patientVitalSignsModel.ModValue))
                            {
                                patientVitalSignsModel.ModValue = "";
                            }
                            return;
                        }
                    }
                    if (!DataManager.Instance.CurrentHospital.HospitalCode.Equals(HospitalConfig.HOSPITAL_CODE_CQ_TLRMYY))
                    {
                        //有创血压存储
                        if (patientVitalSignsModel.Code.Equals(Constants.PARAM_IBP_S) && !string.IsNullOrEmpty(patientVitalSignsModel.ModValue))
                        {
                            if (BedsideMapMap.ContainsKey(Constants.PARAM_NIBP_S))
                            {
                                if (!string.IsNullOrEmpty(BedsideMapMap[Constants.PARAM_NIBP_S][patientVitalSignsModel.CaptureTime].ModValue))
                                {
                                    BedsideMapMap[Constants.PARAM_NIBP_S][patientVitalSignsModel.CaptureTime].ModValue = "";
                                }
                            }
                        }
                        if (patientVitalSignsModel.Code.Equals(Constants.PARAM_IBP_D) && !string.IsNullOrEmpty(patientVitalSignsModel.ModValue))
                        {
                            if (BedsideMapMap.ContainsKey(Constants.PARAM_NIBP_D))
                            {
                                if (!string.IsNullOrEmpty(BedsideMapMap[Constants.PARAM_NIBP_S][patientVitalSignsModel.CaptureTime].ModValue))
                                {
                                    BedsideMapMap[Constants.PARAM_NIBP_D][patientVitalSignsModel.CaptureTime].ModValue = "";
                                }
                            }
                        }
                        if (patientVitalSignsModel.Code.Equals(Constants.PARAM_IBP_M) && !string.IsNullOrEmpty(patientVitalSignsModel.ModValue))
                        {
                            if (BedsideMapMap.ContainsKey(Constants.PARAM_NIBP_M))
                            {
                                if (!string.IsNullOrEmpty(BedsideMapMap[Constants.PARAM_NIBP_S][patientVitalSignsModel.CaptureTime].ModValue))
                                {
                                    BedsideMapMap[Constants.PARAM_NIBP_M][patientVitalSignsModel.CaptureTime].ModValue = "";
                                }
                            }
                        }

                        //无创血压存储
                        if (patientVitalSignsModel.Code.Equals(Constants.PARAM_NIBP_S) && !string.IsNullOrEmpty(patientVitalSignsModel.ModValue))
                        {
                            if (BedsideMapMap.ContainsKey(Constants.PARAM_IBP_S))
                            {
                                if (!string.IsNullOrEmpty(BedsideMapMap[Constants.PARAM_IBP_S][patientVitalSignsModel.CaptureTime].ModValue) && !string.IsNullOrEmpty(patientVitalSignsModel.ModValue))
                                {
                                    patientVitalSignsModel.ModValue = "";
                                }
                            }
                        }
                        if (patientVitalSignsModel.Code.Equals(Constants.PARAM_NIBP_D) && !string.IsNullOrEmpty(patientVitalSignsModel.ModValue))
                        {
                            if (BedsideMapMap.ContainsKey(Constants.PARAM_IBP_D))
                            {
                                if (!string.IsNullOrEmpty(BedsideMapMap[Constants.PARAM_IBP_D][patientVitalSignsModel.CaptureTime].ModValue) && !string.IsNullOrEmpty(patientVitalSignsModel.ModValue))
                                {
                                    patientVitalSignsModel.ModValue = "";
                                }
                            }
                        }
                        if (patientVitalSignsModel.Code.Equals(Constants.PARAM_NIBP_M) && !string.IsNullOrEmpty(patientVitalSignsModel.ModValue))
                        {
                            if (BedsideMapMap.ContainsKey(Constants.PARAM_IBP_M))
                            {
                                if (!string.IsNullOrEmpty(BedsideMapMap[Constants.PARAM_IBP_M][patientVitalSignsModel.CaptureTime].ModValue) && !string.IsNullOrEmpty(patientVitalSignsModel.ModValue))
                                {
                                    patientVitalSignsModel.ModValue = "";
                                }
                            }
                        }
                    }

                    patientVitalSignsModel.PatientID = CurPatientLink.Id.ToString();

                    //缓存取消之后，非麻醉单界面不再刷新生命体征
                    if (DataManager.Instance.AnesRecordCtrl != null)
                    {

                        if (patientVitalSignsModel.Code.Equals(Constants.PARAM_CTRL_RESP_CODE) || patientVitalSignsModel.Code.Equals(Constants.PARAM_RESP_CODE) || patientVitalSignsModel.Code.Equals(Constants.PARAM_SUB_RESP))
                        {
                            //               patientVitalSignsModel.Group = Constants.RESP;
                            for (int i = 1; i <= DataManager.Instance.CurrentPatientLink.Status.TotalPage; i++)
                            {
                                (DataManager.Instance.AnesRecordCtrl.DataContext as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[i].RealTimeItemCtrlViewModel.RefreshByGroup(Constants.RESP);
                            }

                        }
                        else
                        {
                            for (int i = 1; i <= DataManager.Instance.CurrentPatientLink.Status.TotalPage; i++)
                            {
                                (DataManager.Instance.AnesRecordCtrl.DataContext as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[i].RealTimeItemCtrlViewModel.RefreshByGroup(patientVitalSignsModel.Group);
                            }

                        }

                    }

                    if (patientVitalSignsModel.Code.Equals(Constants.PARAM_SUB_RESP))
                    {
                        patientVitalSignsModel.Code = Constants.PARAM_RESP_CODE;
                    }

                    PatientVitalSignsServicie.Instance.AddUpdate(patientVitalSignsModel);

                    if (patientVitalSignsModel.Code.Equals(Constants.PARAM_RESP_CODE))
                    {
                        if (IsInRespSubTime(patientVitalSignsModel.CaptureTime))
                        {
                            if (!string.IsNullOrEmpty(patientVitalSignsModel.ModValue))
                            {
                                patientVitalSignsModel.Code = Constants.PARAM_SUB_RESP;
                            }
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Common.LogHelper.Error(this.GetType(), ex);
                }
            }
        }

        protected override void AddBedsideHistoryData(Dictionary<DateTime, PatientVitalSignsModel> bedsideMap, ConfigVitalSignsModel vitalSigns, DateTime date)
        {
            {
                DateTime endData;
                if (!CurPatientLink.Status.OutRoomTime.Equals(new DateTime()))
                {
                    endData = CurPatientLink.Status.OutRoomTime;
                }
                else
                {
                    endData = date;
                }
                DateTime startData = date.AddMinutes(-1).AddHours(-4 * CurTotalPage);
                if (!CurPatientLink.Status.InRoomTime.Equals(new DateTime()))
                {
                    if (startData < CurPatientLink.Status.InRoomTime)
                    {
                        startData = CurPatientLink.Status.InRoomTime;
                    }
                }
                List<PatientVitalSignsModel> bedsides = PatientVitalSignsServicie.Instance.GetByTimeACode(CurPatientLink.Id.ToString(), vitalSigns.code, startData, endData);

                for (int i = bedsides.Count - 1; i >= 0; i--)
                {
                    if (Constants.ISLABOR.Equals(bedsides[i].IsAorP))
                    {
                        bedsides.Remove(bedsides[i]);
                    }
                }
                foreach (PatientVitalSignsModel bedside in bedsides)
                {
                    SetValue(bedsideMap, bedside);

                }

            }

        }

        protected override void InitRespSubTime()
        {
            {
                List<PatientEventsModel> events = EventData.SearchEventExeByCode(Constants.EVENT_SUB_REST);
                if (events != null && events.Count > 0)
                {
                    events.Sort((PatientEventsModel o1, PatientEventsModel o2) =>
                    {
                        if (o1.BeginTime > o2.BeginTime)
                        {
                            return 1;
                        }
                        if (o1.BeginTime < o2.BeginTime)
                        {
                            return -1;
                        }
                        else
                        {
                            return 0;
                        }
                    });
                    _respSubEventList = events;
                    IsSubResp = true;

                    for (int i = 1; i <= CurTotalPage; i++)
                    {
                        (DataManager.Instance.AnesRecordCtrl.DataContext as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[i].RealTimeItemCtrlViewModel.ChangeVitalTotal();
                    }
                }
                else
                {
                    IsSubResp = false;
                    for (int i = 1; i <= CurTotalPage; i++)
                    {
                        (DataManager.Instance.AnesRecordCtrl.DataContext as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[i].RealTimeItemCtrlViewModel.ChangeVitalTotal();
                    }
                }
            }
        }
        protected override void InitRespCtrlTime()
        {

            List<PatientEventsModel> events = EventData.SearchEventExeByCode(Constants.EVENT_CTRL_REST);
            if (events != null && events.Count > 0)
            {
                events.Sort((PatientEventsModel o1, PatientEventsModel o2) =>
                {
                    if (o1.BeginTime > o2.BeginTime)
                    {
                        return 1;
                    }
                    if (o1.BeginTime < o2.BeginTime)
                    {
                        return -1;
                    }
                    else
                    {
                        return 0;
                    }
                });
                RespCtrlEventList = events;
            }
        }
        protected override bool IsInRespCtrlTime(DateTime captureTime)
        {
            bool flag = false;
            if (RespCtrlEventList != null && RespCtrlEventList.Count > 0)
            {
                for (int i = 0; i < RespCtrlEventList.Count; i++)
                {
                    PatientEventsModel pem = RespCtrlEventList[i];
                    if (!pem.BeginTime.Equals(new DateTime()))
                    {
                        if (pem.EndTime.Equals(new DateTime()))
                        {
                            if (captureTime >= pem.BeginTime)
                            {
                                flag = true;
                            }
                        }
                        else
                        {
                            if (captureTime >= pem.BeginTime && captureTime <= pem.EndTime)
                            {
                                flag = true;
                            }
                        }
                    }

                }
            }
            return flag;
        }

        protected override bool IsInRespSubTime(DateTime captureTime)
        {
            bool flag = false;
            if (_respSubEventList != null && _respSubEventList.Count > 0)
            {
                for (int i = 0; i < _respSubEventList.Count; i++)
                {
                    PatientEventsModel pem = _respSubEventList[i];
                    if (!pem.BeginTime.Equals(new DateTime()))
                    {
                        if (pem.EndTime.Equals(new DateTime()))
                        {
                            if (captureTime >= pem.BeginTime)
                            {
                                flag = true;
                            }
                        }
                        else
                        {
                            if (captureTime >= pem.BeginTime && captureTime <= pem.EndTime)
                            {
                                flag = true;
                            }
                        }
                    }

                }
            }
            return flag;
        }

        public override void RefreshRespEvent()
        {

            ClearResp();
            //刷新时间
            InitRespSubTime();
            InitRespCtrlTime();
            //重新排列数据
            InitSubRespData();
            InitCtrlRespData();

            for (int i = 1; i <= DataManager.Instance.CurrentPatientLink.Status.TotalPage; i++)
            {
                (DataManager.Instance.AnesRecordCtrl.DataContext as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[i].RealTimeItemCtrlViewModel.RefreshByGroup(Constants.RESP);
            }

        }
        protected override PatientVitalSignsModel CreateBedside(ConfigVitalSignsModel vitalSigns, DateTime date)
        {
            PatientVitalSignsModel patientVitalSigns = new PatientVitalSignsModel();
            patientVitalSigns.IsAorP = Constants.ISANES;
            patientVitalSigns.Code = vitalSigns.code;
            patientVitalSigns.Name = vitalSigns.name;
            patientVitalSigns.DataType = vitalSigns.dataType;
            patientVitalSigns.CaptureTime = date;
            patientVitalSigns.Scale = vitalSigns.scale;
            patientVitalSigns.UnitName = vitalSigns.unitName;
            patientVitalSigns.PatientID = CurPatientLink.Id.ToString();
            patientVitalSigns.ModValue = "";
            return patientVitalSigns;
        }


        protected override void ChangeVitalCache(PatientVitalSignsModel pvm)
        {
            try
            {
                if (!pvm.PatientID.Equals(PatientId))
                {
                    return;
                }
                bool flag = false;
                if (!CurPatientLink.Status.OutRoomTime.Equals(new DateTime()))
                {
                    return;
                }
                if (BedsideMapMap.ContainsKey(pvm.Code))
                {
                    Dictionary<DateTime, PatientVitalSignsModel> bedsideMap = BedsideMapMap[pvm.Code];
                    //if (Constants.PARAM_RESP_CODE.Equals(pvm.Code) || Constants.PARAM_CTRL_RESP_CODE.Equals(pvm.Code))
                    //{
                    //    pvm = CovertResp(pvm);
                    //}
                    if (!string.IsNullOrEmpty(pvm.ModValue) && bedsideMap.ContainsKey(pvm.CaptureTime))
                    {

                        SynchronizationContext.SetSynchronizationContext(new
                          DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
                        SynchronizationContext.Current.Post(pl =>
                        {
                            bedsideMap[pvm.CaptureTime].ModValue = pvm.ModValue;
                        }, null);

                        flag = true;
                    }
                }
                if (!flag)
                {
                    PatientVitalSignsServicie.Instance.AddUpdate(pvm);
                }
            }
            catch (Exception ex)
            {

                Common.LogHelper.Error(this.GetType(), ex);
            }

        }

       


        #endregion


        #region EventHandlers


        #endregion

    }
}
